import config from '@/config'
/**
* @description 二次封装localStorage
* @author LoneWolf
*/

export default {
    getStorage () {
        let storage = JSON.parse(localStorage.getItem(config.nameSpace)) || {}
        // 判断storage是否为对象
        if (Object.prototype.toString.call(storage) !== '[object Object]') storage = {}
        return storage
    },
    getItem (key) {
        return this.getStorage()[key] || null
    },
    setItem (obj) {
        const storage = this.getStorage()
        // 检测obj是否是对象
        if (Object.prototype.toString.call(obj) === '[object Object]') {
            Object.assign(storage, obj)
        } else if (Array.isArray(obj)) {
            obj.forEach(item => {
                // console.log(Object.keys(item)[0])
                storage[Object.keys(item)[0]] = item.value
            })
        } else {
            throw new Error('参数必须是对象或者数组')
        }
        localStorage.setItem(config.nameSpace, JSON.stringify(storage))
    },
    removeItem (key) {
        const storage = this.getStorage()
        delete storage[key]
        localStorage.setItem(config.nameSpace, JSON.stringify(storage))
    },
    clear () {
        localStorage.removeItem(config.nameSpace)
    }

}
